//
//  YZXLoginController.swift
//  YZXWeibo
//
//  Created by 叶周翔 on 16/7/19.
//  Copyright © 2016年 叶周翔. All rights reserved.
//

import UIKit
import SVProgressHUD


class YZXLoginController: UIViewController {
    
    override func loadView() {
        self.view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.whiteColor()
        // 设置代理
        self.webView.delegate = self
        self.setUpNavBar()
        SVProgressHUD.showWithStatus("正在加载")
        
        
        // 加载一个webView
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url:NSURL = NSURL(string: urlString)!
        let request = NSURLRequest(URL:url)
        webView.loadRequest(request)
        
    }
    
    
    // MARK:导航相关方法
    func setUpNavBar(){
        // 设置导航栏的状态
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "addFull")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        self.navigationItem.title = "登录"
    }

    @objc private func addFull() {
          let jsCode = "document.getElementById('userId').value='darlingyzx@sina.com';document.getElementById('passwd').value='yzx.yzx-13125'"
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
    
    @objc private func close() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 懒加载控件
    private lazy var webView:UIWebView = UIWebView()
    
}


// MARK: - UIWebViewDelegate
extension YZXLoginController:UIWebViewDelegate{
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
//        print(urlString)
        
        if !urlString.hasPrefix(redirect_uri) {
            // 如果不是授权回调地址 就是不是百度的地址那么就去加载
            return true
        }else{
            // 授权回调地址
            
            /*
            取消：
            "http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330"
            
            授权:http://www.baidu.com/?code=d0f624baad79ee9eb43f06c789aa4298
            
            */
            
            let quey = request.URL!.query
            
            // 判断后面的参数是否是code结尾的
            let codeString = "code="
            if quey!.hasPrefix(codeString){
                
//                print("授权")
                // 先装换成NSString 类型的字符串
                let nsQuey = quey! as NSString
                // 截取字符串
                let code = nsQuey.substringFromIndex(codeString.characters.count)
//                print(code)
                // 调用方法
                YZXUserAccountVM.shareUserAccountVM.loadAccess_Token(code)
                // 跳转控制器
                AppDelegate.jumpToOtherController(YZXWelcomeController())
                
            }else{
                print("点击了取消")
            }
            
            // 返回false 拦截操作
            return false
            
        }
        
        
    }
    
//    func loadAccess_Token(code:String) -> Void{
//        
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        // 请求参数
//        let paraments = [
//            "client_id": client_id,
//            "client_secret": client_secret,
//            "grant_type": "authorization_code",
//            "code": code,
//            "redirect_uri": redirect_uri
//        ]
//        
//        // 使用afn发送POST请求
//        YZXNetworkTool.shareNetworkTool.POST(urlString, parameters: paraments, progress: nil, success: { (_, resopnseOjbect) -> Void in
//            
//            print("\(resopnseOjbect)")
//            
//            
//            
//            }) { (_, error) -> Void in
//                
//                print("\(error)")
//        }
//        
//        
//    }
//    
    
}



